<script setup lang="jsx">
import { nextTick, ref } from 'vue';
import dayjs from 'dayjs';
import { UUID } from 'uuidjs';
import Modal from '@/components/common/modal.vue';
import { getLayerSelect } from '@/service/api/modules/collection-management/hole-inspection';
import {
  monthPlanCapacityTarget,
  monthPlanCapacityTargetAdd,
  monthPlanCapacityTargetDelete,
  monthPlanCapacityTargetEdit
} from '@/service/api/modules/plan';

import AddForm from './modules/add.vue';

const commonSearchRef = ref(null);
const searchParams = ref({
  layer: null,
  deliverytarget: null,
  time: dayjs(new Date()).format('YYYY-MM') // 默认查询当月
});

const layerList = ref([]);
const searchFormList = [
  {
    type: 'select',
    key: 'layer',
    label: '层数',
    placeholder: '请选择层数',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 5,
    // 下拉选择框选项
    selectOptions: layerList
  },
  {
    type: 'datePicker',
    key: 'time',
    label: '年月',
    placeholder: '请输入年月',
    span: 24,
    md: 12,
    lg: 8,
    xl: 8,
    xxl: 5,
    picker: 'month',
    format: 'YYYY-MM',
    valueFormat: 'YYYY-MM'
  }
];
// 下拉列表接口：
function getSystemList() {
  getLayerSelect().then(({ data, error }) => {
    layerList.value = data?.map(item => {
      return {
        label: item,
        value: item
      };
    });
  });
}
getSystemList();

const flexedColumns = [
  {
    key: 'layer',
    dataIndex: 'layer',
    title: '层数',
    fixed: 'left',
    width: 100,
    align: 'center',
    checked: true,
    ellipsis: true
  },
  {
    key: 'deliverytarget',
    dataIndex: 'deliverytarget',
    title: (
      <span
        style="color: #0000ff;
             font-weight: 600;
            font-size: larger;"
      >
        交货目标产量
      </span>
    ),
    width: 130,
    fixed: 'left',
    align: 'center',
    checked: true,
    ellipsis: true,
    className: 'data-cell-sum'
  }
];
const arrlast = [
  {
    key: 'operator',
    dataIndex: 'operator',
    title: '创建人',
    width: 80,
    align: 'center',
    checked: true
  },
  {
    key: 'createDate',
    dataIndex: 'createDate',
    title: '创建时间',
    width: 150,
    align: 'center',
    checked: true
  },
  {
    key: 'updateUser',
    dataIndex: 'updateUser',
    title: '修改人',
    width: 80,
    align: 'center',
    checked: true
  },
  {
    key: 'updateDate',
    dataIndex: 'updateDate',
    title: '修改时间',
    width: 150,
    align: 'center',
    checked: true
  }
];

const columns = ref([]);
const formState = ref({});
const closetable = ref(false);

const tableData = ref([]);
const loading = ref(false);
const addFormRef = ref(null);

function getData() {
  const params = {
    layer: searchParams.value.layer,
    deliverytarget: searchParams.value.deliverytarget,
    month: searchParams.value.time
  };
  if (searchParams.value.time?.[0]) {
    params.startTime = searchParams.value.time[0];
  } else {
    window.$message.error('请选择计划月份');
    return;
  }
  loading.value = true;

  monthPlanCapacityTarget({ startDate: searchParams.value.time, ...searchParams.value })
    .then(res => {
      console.log('res', res);

      const arr = [];
      res.header.forEach((item, index) => {
        arr.push({
          key: `day${Number(item.split('-')[2])}`,
          dataIndex: `day${Number(item.split('-')[2])}`,
          title: item,
          width: 130,
          align: 'center',
          checked: true,
          ellipsis: true,
          type: 'number'
        });
      });
      tableData.value = res.tableData.map(item => {
        return {
          ...item,
          tableUUid: UUID.generate()
        };
      });
      columns.value = [...flexedColumns, ...arr, ...arrlast];
      console.log('columns.value ', columns.value);

      console.log('tableData', tableData.value);
    })
    .finally(() => (loading.value = false));
}
getData();

function search() {
  getData();
}

const formTit = ref('');
const selectedRowKeys = ref([]);

const eidtData = ref(null);

// 新增
function manualSyncing() {
  formState.value = {};
  closetable.value = true;
  formTit.value = '月计划产能目标新增';
}

// 新增/修改弹窗提交
// monthPlanCapacityTargetEdit
async function boundUpdata(val) {
  const form = { ...addFormRef.value };
  await form.validateForm();
  // formData是表单数据
  const formData = form.topFormModel;

  if (val === '月计划产能目标新增') {
    monthPlanCapacityTargetAdd(formData).then(({ data, error }) => {
      if (!error) {
        window.$message?.success('新增成功');
        closetable.value = false;
        // getData();
      }
    });
  } else {
    monthPlanCapacityTargetEdit(formData).then(({ data, error }) => {
      if (!error) {
        window.$message?.success('修改成功');
        selectedRowKeys.value = [];
        eidtData.value = null;
        closetable.value = false;
        // getData();
      }
    });
  }
  // 清空表单
  topFormModel.value.deliverytarget = '';
}
// 修改
function updateSyncing() {
  if (selectedRowKeys.value.length !== 1) {
    return window.$message?.error('请选择一条数据');
  }
  formTit.value = '月计划产能目标修改';
  eidtData.value = selectedRowKeys.value[0];
  closetable.value = true;
  // nextTick(() => {
  //   addFormRef.value.setForm(tableData.value);
  // });
}

// 删除
function deleteSyncing() {
  if (selectedRowKeys.value.length == 0) {
    return window.$message?.error('请选择数据');
  }
  window.$modal.confirm({
    title: '提醒',
    content: '确认删除所选数据吗？',
    onOk: () => {
      const deleteData = selectedRowKeys.value;
      monthPlanCapacityTargetDelete(deleteData).then(({ error, data }) => {
        if (!error) {
          window.$message?.success('删除成功');
          selectedRowKeys.value = [];
          getData();
        }
      });
    },
    onCancel: () => {}
  });
}
getData();

function handleTableSelectChange(val) {
  selectedRowKeys.value = val;
}

function reset() {
  nextTick(() => {
    searchParams.value = {
      layer: null,
      time: dayjs(new Date()).format('YYYY-MM') // 默认查询当月
    };
    search();
  });
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CommonSearch
      ref="commonSearchRef"
      v-model:searchParams="searchParams"
      :form-list="searchFormList"
      :is-search="true"
      @search="search"
      @reset="reset"
    ></CommonSearch>

    <Table
      :row-class-name="rowClassName"
      header-class-name="custom-header"
      :column="columns"
      :data-source="tableData"
      :loading="loading"
      :summary-fixed="true"
      row-key="tableUUid"
      :row-height="55"
      :scroll="{ y: 'auto' }"
      :is-pagination="false"
      class="h-full"
      :show-row-selection="true"
      @table-select-change="handleTableSelectChange"
    >
      <template #title>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="manualSyncing">
          <template #icon>
            <icon-ic-round-add class="align-sub text-icon" />
          </template>
          <span class="ml-3px">新增</span>
        </AButton>
        <AButton
          type="primary"
          size="small"
          ghost
          class="mini-btn mr-8px"
          :disabled="selectedRowKeys.length !== 1"
          @click="updateSyncing"
        >
          <template #icon>
            <icon-ic-round-edit class="align-sub text-icon" />
          </template>
          <span class="ml-3px">修改</span>
        </AButton>
        <AButton type="primary" size="small" ghost class="mini-btn mr-8px" @click="deleteSyncing">
          <template #icon>
            <icon-ic-round-delete class="align-sub text-icon" />
          </template>
          <span class="ml-3px">删除</span>
        </AButton>
      </template>
      <!-- 底部合计 -->
      <template #summary>
        <STableSummaryRow>
          <STableSummaryCell :index="0" :col-span="2" class="text-center">
            <div>
              <span style="font-size: 26px; font-weight: 600">总合计</span>
            </div>
          </STableSummaryCell>
          <STableSummaryCell :index="2" class="text-center">
            <template #default="{ total }">
              <span style="font-size: 20px; font-weight: 400">{{ total }}</span>
            </template>
          </STableSummaryCell>
        </STableSummaryRow>
      </template>
    </Table>
    <Modal
      v-model:visible="closetable"
      :destroy-on-close="true"
      :centered="true"
      :title="formTit"
      width="1200px"
      height="730px"
    >
      <div class="h-full w-full">
        <AddForm ref="addFormRef" :row-data="eidtData"></AddForm>
      </div>

      <template #footer>
        <div class="modal-footer">
          <AButton @click="closetable = false">关闭</AButton>
          <AButton type="primary" @click="boundUpdata(formTit)">保存</AButton>
        </div>
      </template>
    </Modal>
  </div>
</template>

<style>
.data-cell-sum {
  color: #3e3e79;
  font-weight: 600;
}
</style>
